<?php

class Serial_productsController extends AdminController {

    public function filters() {
        return array(
            'accessControl',
        );
    }

    public function actionDownload() {

        $rs_serial_products = Yii::app()->db->createCommand()
                ->select('serial_products_id, serial_products_pin')
                ->from('sys_serial_products')
                ->where('UNIX_TIMESTAMP(serial_products_create_datetime)=:id', array(':id' => $_GET['id']))
                ->order('serial_products_id ASC')
                ->queryAll();

        $serial_products_create_datetime = Yii::app()->db->createCommand("SELECT FROM_UNIXTIME('" . $_GET['id'] . "') AS datetime")->queryRow();
        $datetime = function_lib::url_title($serial_products_create_datetime['datetime']);

        if ($rs_serial_products) {
            $arr_data[1] = array('Serial Produk', 'PIN');
            foreach ($rs_serial_products as $row_serial_products) {
                array_push($arr_data, array($row_serial_products['serial_products_id'], $row_serial_products['serial_products_pin']));
            }

            Yii::import('application.extensions.phpexcel.JPhpExcel');
            $xls = new JPhpExcel('UTF-8', false, 'Data Serial Produk');
            $xls->addArray($arr_data);
            $xls->generateXML('serial-produk-' . $datetime);
        } else {
            $this->redirect(array('list'));
        }
    }

    public function actionActivate() {
        if (isset($_POST['sys_serial_products'])) {

            $serial_id_start = $_POST['sys_serial_products']['serial_products_id_start'];
            $serial_id_end = $_POST['sys_serial_products']['serial_products_id_end'];
            $option = $_POST['sys_serial_products']['option'];
            $option_message = ($option == 1) ? 'activated' : 'deactivated';
            $datetime = ($option == 1) ? date("Y-m-d H:i:s") : null;
            $serial_is_active = ($option == 1) ? 0 : 1;

            $rs_update = Yii::app()->db->createCommand()->update('sys_serial_products', array(
                'serial_products_active_datetime' => $datetime,
                'serial_products_is_active' => $option,
                    ), "serial_products_id >= :start AND serial_products_id <= :end AND serial_products_is_used = '0' AND serial_products_is_active = :is_active", array(':start' => $serial_id_start, ':end' => $serial_id_end, ':is_active' => $serial_is_active)
            );

            if ($rs_update) {
                Yii::app()->user->setFlash('success', 'Serial Products has been ' . $option_message . '.');
                $this->redirect(array('list'));
            } else {
                Yii::app()->user->setFlash('error', 'Serial Products ' . $option_message . ' failed.');
                $this->redirect(array('activate'));
            }
        }

        $this->render('activate');
    }

    public function actionList() {
        //$model = new sys_serial_products('search');
        /*
         * 1 feb 2012
         * nambah filter list serial
         * serial WARE(3) dan FPRO(4) tidak ditampilkan
         * tanggung jawab mas ardi
         */
        $model = sys_serial_products::model()->with('rel_serial_products_to_serial_product_user')->find('serial_products_products_category_id NOT IN (:var)',array(':var'=> '4'));
        $model->unsetAttributes();
        if (isset($_GET['sys_serial_products']))
            $model->attributes = $_GET['sys_serial_products'];

        $this->render('list', array(
            'model' => $model,
        ));
    }

    public function actionCreate() {
        $model = new sys_serial_products;

        if (isset($_POST['sys_serial_products'])) {
            $last_serial_id = Yii::app()->db->createCommand()
                    ->select('serial_products_id')
                    ->from('sys_serial_products')
                    ->where('serial_products_products_category_id=:id', array(':id' => $_POST['sys_serial_products']['serial_products_products_category_id']))
                    ->order('serial_products_id DESC')
                    ->queryScalar();

            $serial_create_datetime = date("Y-m-d H:i:s");

            $transaction = Yii::app()->db->beginTransaction();
            try {
                for ($i = 1; $i <= $_POST['sys_serial_products']['serial_products_count']; $i++) {

                    $rs_insert = Yii::app()->db->createCommand()->insert('sys_serial_products', array(
                        'serial_products_id' => ++$last_serial_id,
                        'serial_products_products_category_id' => $_POST['sys_serial_products']['serial_products_products_category_id'],
                        'serial_products_pin' => $this->generate_pin(6),
                        'serial_products_create_datetime' => $serial_create_datetime,
                        'serial_products_is_buyed' => '0',
                        'serial_products_is_active' => '0',
                        'serial_products_is_used' => '0',
                            ));
                }
                $id = Yii::app()->db->createCommand("SELECT UNIX_TIMESTAMP('" . $serial_create_datetime . "') AS links_id")->queryRow();
                $transaction->commit();
                Yii::app()->user->setFlash('success', 'Serial successfully generated. Please <a href="' . Yii::app()->baseUrl . '/admin/system/serial_products/download/' . $id['links_id'] . '">download file excel</a>.');
                $this->redirect(array('list'));
            } catch (CDbException $e) {
                $transaction->rollback();
                Yii::app()->user->setFlash('error', 'Generate serial failed.');
                $this->redirect(array('create'));
            }
        }

        $this->render('create', array(
            'model' => $model,
        ));
    }

    public function actionView() {
        $id = function_lib::uri_segment(5);
        
        if ($id != '') {
            $model = sys_serial_products::model()->findByAttributes(array("serial_products_id" => $id));

            $this->render('view', array(
                'model' => $model,
            ));
        } else {
            throw new CHttpException(404, 'The requested page does not exist.');
        }
    }

    public function loadModel($id) {
        $model = sys_serial_products::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    private function generate_pin($char_length) {
        $pin = '';
        $pin_str = "1234567809";

        for ($i = 0; $i < strlen($pin_str); $i++) {
            $pin_chars[$i] = $pin_str[$i];
        }

        // randomize the chars
        srand((float) microtime() * 1000000);
        shuffle($pin_chars);

        for ($i = 0; $i < 20; $i++) {
            $char_num = rand(1, count($pin_chars));
            $pin .= $pin_chars[$char_num - 1];
        }
        $pin = substr($pin, 0, $char_length);

        return $pin;
    }

}